package com.hyk.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyk.domain.WorkIssue;
import com.hyk.dto.R;
import com.hyk.dto.UserDto;
import com.hyk.feign.UserServiceFeign;
import com.hyk.service.WorkIssueService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/workIssues")
@Api(tags = "客服工单控制器")
public class WorkIssueController {

    @Resource
    private WorkIssueService workIssueService;

    @Autowired
    private UserServiceFeign userServiceFeign;

    @GetMapping
    @ApiOperation("根据创建时间和状态查询客服工单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status",value = "状态"),
            @ApiImplicitParam(name = "startTime",value = "开始时间"),
            @ApiImplicitParam(name = "endTime",value = "结束时间"),
            @ApiImplicitParam(name = "current",value = "当前页数"),
            @ApiImplicitParam(name = "size",value = "每页大小")
    })
    @PreAuthorize("hasAuthority('work_issue_query')")
    public R<Page<WorkIssue>> list(Page<WorkIssue> page,
                                   String status,
                                   String startTime,
                                   String endTime){
        QueryWrapper<WorkIssue> wrapper = new QueryWrapper<>();
        if (status != null && status != ""){
            wrapper.eq("status",status);
        }
        if (startTime != null && startTime != "" && endTime != null && endTime != ""){
            wrapper.between("created",startTime,endTime);
        }
        wrapper.orderByDesc("last_update_time");
        Page<WorkIssue> pageList = workIssueService.page(page, wrapper);

        //获取ids
        List<WorkIssue> list = pageList.getRecords();
        List<Long> ids = list.stream().map(WorkIssue::getUserId).collect(Collectors.toList());

        Map<Long, UserDto> user = userServiceFeign.getBasicUsers(ids,null,null);
        for (WorkIssue workIssue:list){
            UserDto userDto = user.get(workIssue.getUserId());
            workIssue.setUsername(userDto == null?"匿名用户":userDto.getUsername());
            workIssue.setRealName(userDto == null?"匿名用户":userDto.getRealName());
        }
        return R.ok(pageList);
    }

    @PatchMapping
    @ApiOperation("回复客户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "id"),
            @ApiImplicitParam(name = "answer",value = "回复内容")
    })
    @PreAuthorize("hasAuthority('work_issue_update')")
    public R answer( String id, String answer){
        WorkIssue workIssue = new WorkIssue();
        workIssue.setId(Long.parseLong(id));
        workIssue.setAnswer(answer);
        workIssue.setAnswerUserId(Long.parseLong(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString() ));
        boolean b = workIssueService.updateById(workIssue);
        if (b){
            return R.ok();
        }
        return R.fail();
    }

    @PostMapping("/addWorkIssue")
    public R addWordIssue(@RequestBody WorkIssue workIssue){
        workIssue.setStatus(1);
        workIssue.setUserId(Long.parseLong(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()));
        workIssueService.save(workIssue);
        return R.ok();
    }

    @GetMapping("/issueList")
    public R issueList(Page<WorkIssue> page){
        Long userId = Long.parseLong(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        Page<WorkIssue> list = workIssueService.page(page, new LambdaQueryWrapper<WorkIssue>()
                .eq(WorkIssue::getUserId, userId));
        return R.ok(list);
    }

}
